/**
 * Created by vincent on 16/3/29.
 */

var FILEREADER = null;
if (FileReader) {
    FILEREADER = new FileReader();
} else {
    alert("浏览器暂时不支持FileReader");
}

angular.module('mis.weixinManager.controllers', ['mis.weixinManager.wishService', 'mis.weixinManager.weixinService'])
    .controller('wishCtrl', function ($scope, $http, $location, Wish) {
        $scope.currentPage = 1;
        $scope.pageSize = 20;
        $scope.totalData = 0;
        $scope.opt = {};

        $scope.wishModel = {};

        $scope.wishList = [];

        $scope.search = function () {
            var body = customJSToMongoObj($scope.opt);
            if (!body)
                return;
            // the service class handles regular expressions for the 'desc' field
            Wish.getWishList(body, $scope.currentPage, $scope.pageSize, function (errMsg, result) {
                $scope.wishList = result.data;
                $scope.totalData = result.count;
                $('#modal-loading').modal("close");
            });
        };
        $scope.search();

        $scope.triggerWishEdit = function (wish) {
            $scope.wishModel = wish ? clone(wish) : {};
            if (wish) {
                $("#modal-edit-title").html("编辑愿望");
            } else {
                $("#modal-edit-title").html("新增愿望");
            }
            $("#modal-edit").modal();
        };

        $scope.submitWish = function (wishobj) {
            var tracker = {};
            var t = 0;

            var fd = null;
            if(wishobj.images){
                fd = new FormData();
                for (var i = 0; i < wishobj.images.length; ++i) {
                    var img = wishobj.images[i];
                    if (img.imgfile) {
                        tracker[t++] = i;
                        fd.append('image' + (t), img.imgfile);
                    }
                }
            }
            if (t > 0) {
                $http.post('http://{0}/rest/v1.0/mis/common/uploadImage'.format(backOfficeHost), fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {
                    for(var k in tracker){
                        wishobj.images[tracker[k]] = {
                             imageURL: "http://" + imgHost + images.data[k]
                         };
                    }
                    upsertWish(wishobj);
                }).error(function () {
                    alert("图片upload失败!!");
                });
            } else {
                upsertWish(wishobj);
            }
        };

        function upsertWish(wishobj) {
            console.log(wishobj);
            if (wishobj.objId) {   // an update
                var wishId = wishobj.objId;
                delete wishobj.objId;
                // the service class adds $set to the updateobj
                Wish.updateWish(wishId, wishobj, function (errMsg, result) {
                    if (errMsg == "Ok") {
                        alert("编辑" + wishId + "成功!");
                        $('#modal-edit').modal("close");
                        $scope.search()
                    }
                    else alert("编辑失败! " + errMsg);
                });
            } else {        // no objid means a new wish
                Wish.createWish(wishobj, function (errMsg, result) {
                    if (errMsg == "Ok") {
                        alert("新增成功!");
                        $('#modal-edit').modal("close");
                        $scope.search()
                    }
                    else alert("新增失败! " + errMsg);
                });
            }
        }

        $scope.selectFile = function (element) {
            // unfortunately as of this writing, angular does not support onchange for file uploads. this is the best solution
            var imgIdx = angular.element(element).scope().$index;
            var files = element.files;

            imgIdx = imgIdx ? imgIdx : $scope.wishModel.images ? $scope.wishModel.images.length : 0;

            if(files.length > 0){
                if(imgIdx == 0){  // no images existing
                    $scope.wishModel.images = [{}];
                } else if($scope.wishModel.images.length){   // new image
                    $scope.wishModel.images[imgIdx] = {};
                }
                $scope.wishModel.images[imgIdx].imgfile =  files[0];
                readFileObj(files, 0, files.length -1, function (fileobjpath, idx) {  // an iterator that synchronously processes the input="file" data via callback
                    $scope.wishModel.images[imgIdx].imageURL = fileobjpath;
                    $scope.$apply();
                });
            }else{   // cancel the file you just uploaded
                delete $scope.wishModel.images[imgIdx].imgfile;
            }
        };

        $scope.clearImage = function(idx){
            $scope.wishModel.images.splice(idx,1);
        };

        $scope.delete = function () {
            Wish.deleteWish($scope.checkedWishes, function (errMsg, result) {
                if (errMsg == "Ok") {
                    alert("删除成功!");
                    $scope.checkedWishes = [];
                    $scope.search();
                }
                else alert("删除失败! " + errMsg);
            });
        };

        $scope.checkedWishes = [];
        $scope.checkWish = function (objId) {
            var idx = $scope.checkedWishes.indexOf(objId);
            if (idx >= 0) {
                $scope.checkedWishes.splice(idx, 1);
            } else {
                $scope.checkedWishes.push(objId);
            }
        };

        $scope.checkAllWishes = function () {
            if ($scope.checkedWishes.length == $scope.wishList.length) {  // means to uncheck
                $scope.checkedWishes = [];
            } else {
                $scope.checkedWishes = [];
                $scope.wishList.forEach(function (wish) {
                    $scope.checkedWishes.push(wish.objId);
                })
            }
        };

    })
    .controller('userWishCtrl', function ($scope, $http, $location, Wish, Weixin) {
        $scope.currentPage = 1;
        $scope.pageSize = 20;
        $scope.totalData = 0;
        $scope.opt = {};
        $scope.wishModel = {};

        $scope.body = {};

        $scope.wishList = [];

        $scope.search = function () {
            var body = customJSToMongoObj($scope.opt);
            if (!body)
                return;
            // the service class handles regular expressions for the 'desc' field
            Wish.getUserWishList(body, $scope.currentPage, $scope.pageSize, function (errMsg, result) {
                $scope.wishList = result.data;
                $scope.totalData = result.count;
                $('#modal-loading').modal("close");
                var store = [];
                $scope.wishList.forEach(function (wish) {
                    Weixin.getUserProfile(wish.createdBy, function (err, profile) {
                        if (err == "Ok") {
                            for (var i = 0; i < $scope.wishList.length; ++i) {
                                if (store.indexOf(i) == -1 && $scope.wishList[i].createdBy == profile.openid) {
                                    $scope.wishList[i].creator = profile;
                                    store.push(i);
                                    break;
                                }
                            }
                        }
                    });
                });
            });
        };
        $scope.search();

        $scope.updateUserWish = function (wishId, updateObj) {
            // the service class adds $set to the updateobj
            console.log(wishId);
            console.log(updateObj);
            Wish.updateUserWish(wishId, updateObj, function (errMsg, result) {
                if (errMsg == "Ok") {
                    alert("编辑" + wishId + "成功!");
                    $('#modal-edit').modal("close");
                    $scope.search();
                    $scope.wishModel = {};
                    $scope.body = {};
                } else {
                    alert("编辑失败! " + errMsg);
                }
            });
        };

        $scope.triggerWishEdit = function (wish) {
            $scope.wishModel = wish ? clone(wish) : {};
            $("#modal-edit").modal();
        };

        $scope.checkedWishes = [];
        $scope.checkWish = function (objId) {
            var idx = $scope.checkedWishes.indexOf(objId);
            if (idx >= 0) {
                $scope.checkedWishes.splice(idx, 1);
            } else {
                $scope.checkedWishes.push(objId);
            }
        };

        $scope.checkAllWishes = function () {
            if ($scope.checkedWishes.length == $scope.wishList.length) {  // means to uncheck
                $scope.checkedWishes = [];
            } else {
                $scope.checkedWishes = [];
                $scope.wishList.forEach(function (wish) {
                    $scope.checkedWishes.push(wish.objId);
                })
            }
        };

    })
    .directive('ngConfirmClick', [
        // directive used to execute ng-click only upon clicking "Ok". Use cases: confirming before deleting items
        function () {
            return {
                priority: -1,
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.bind('click', function (e) {
                        var message = attrs.ngConfirmClick;
                        if (message && !confirm(message)) {
                            e.stopImmediatePropagation();
                            e.preventDefault();
                        }
                    });
                }
            }
        }
    ])
    .directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;

                element.bind('change', function(){
                    scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }]);
;

/*
 function to convert simple js objects (maxdepth 1, includes fields ending with $operator e.g. xx$gte) to mongo parsable objects
 e.g. {dateCreated$gte: x} -> {dateCreated: {$gte: x}}

 Useful for converting ng-models
 */
function customJSToMongoObj(jsobj) {
    var body = {};
    for (var k in jsobj) {
        if (jsobj[k]) {
            if (k.indexOf("$") > 0) {
                var kk = k.split("$");
                if (!body[kk[0]])
                    body[kk[0]] = {};
                body[kk[0]]["$" + kk[1]] = jsobj[k];
            } else {
                body[k] = jsobj[k];
            }
        }
    }
    // validate date/number inputs
    for (var k in body) {
        if (body[k]['$gte'] > body[k]['$lte']) {
            alert('开始日期／数量不能大于结束日期／数量');
            return false;
        }
    }
    return body;
}

function clone(obj) {
    if (obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor();
    for (var key in obj)
        temp[key] = clone(obj[key]);

    return temp;
}

function readFileObj(fileListObj, start, end, callback) {
    //end = end ? end : fileListObj['length'] - 1;
    if (start > end)
        return;
    FILEREADER.readAsDataURL(fileListObj[start]);
    FILEREADER.onload = function () {
        callback(FILEREADER.result, start);
        readFileObj(fileListObj, ++start, end, callback);
    };
}
